import {clearObject,deepCopyObj,copyObjBySelf} from '../../../assets/js/help.js'
export default {
  data () {
    var checkLoginId = (rule, value, callback) => {
      if(value==='') {
        callback(new Error('请输入用户名'));
      }else{
        var regexp = /^[a-zA-Z0-9_.]+$/;
        var result = regexp.test(value);
        if (!result) {
          callback(new Error('用户名仅支持英文字符、数字、特殊符号._组合'));
        } else {
          API.platform_manage.CheckLoginId({'loginId':value}).then(res => {
            if (res.status == 1) {
              if(res.data){
                callback();
              }else{
                callback(new Error('此用户名已被占用'));
              }
            } else {
              callback(new Error('验证错误，系统繁忙'));
            }
          }, err => { });
        }
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.userForm.passWord !== '') {
          var regexp = /^[a-zA-Z0-9~!@#$%^&*()_<>]+$/;
          var result = regexp.test(value);
          console.log(result);
          if(result){
            callback();
          }else{
            callback(new Error('新密码仅支持英文字符、数字、特殊符号~!@#$%^&*()_<>组合'));
          }
        }
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.userForm.passWord) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var resetvalidatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.pwdForm.password !== '') {
          var regexp = /^[a-zA-Z0-9~!@#$%^&*()_<>]+$/;
          var result = regexp.test(value);
          console.log(result);
          if(result){
            callback();
          }else{
            callback(new Error('用户密码仅支持英文字符、数字、特殊符号~!@#$%^&*()_<>组合'));
          }
        }
      }
    };
    var resetvalidatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.pwdForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      totalPowerNum: 0, //权限总数
      isAllCheck: false, //全选-反选
      checkedSum: 0, //选中的项数
      dialogVisibleForUser: false, //新增用户框是否显示
      dialogVisibleForRole: false, //新增角色
      dialogVisibleForGroup: false, //新增分组
      tabIndex: 1,//(1:创建用户;2:设置角色;3:绑定分组)
      tabIndexForRole: 1, //(1:创建角色;2:设置权限)
      tabIndexForGroup: 1, //(1:创建分组;2:选择停车场)
      allRoleList: [], //所有角色
      allGroupList: [], //所有分组
      chooseRoleList:[], //选择的角色列表
      chooseGroupList:[], //选择的分组列表
      userId:"",
      userForm:{
        loginId:"",passWord:"",passWordAgain:"",nickName:"",mobile:"",email:"",address:""
      },
      userEditForm:{
        loginId:"",nickName:"",mobile:"",email:"",address:"",id:""
      },
      pwdForm:{
        userID:"",loginId:"",password:"",passWordAgain:""
      },
      roleForm:{
        loginId:"",userID:""
      },
      addRoleForm:{id:"",name:"",remark:""},
      roleRules:{
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'change' }
        ],
        remark: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'change' }
        ]
      },
      addGroupForm:{name:'',remark:''},
      groupRules:{
        name: [
          { required: true, message: '请输入分组名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'change' }
        ],
        remark: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'change' }
        ]
      },
      parkGroupForm:{
        loginId:"",userID:""
      },
      leftRoleArr:[],
      rightRoleArr:[],
      leftParkArr:[],
      rightParkArr:[],
      pwdRules:{
         password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'change' },
          { validator: resetvalidatePass, trigger: 'blur' }
        ],
        passWordAgain: [
          { validator: resetvalidatePass2, trigger: 'blur' }
        ],
      },
      rules:{
        loginId: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 10 个字符', trigger: 'change' },
          { validator: checkLoginId, trigger: 'blur' }
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'change' },
          { validator: validatePass, trigger: 'blur' }
        ],
        nickName:[
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 20 个字符', trigger: 'change' }
        ],
        passWordAgain: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        mobile:[
          { min: 0, max: 11, message: '长度在 0 到 50 个字符', trigger: 'blur' },
        ],
        address:[
          { min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur' },
        ]
      }
    }
  },
  created () {
    //this.getList();
  },
  methods: {
    checkAllOrNo(){ //全选-反选方法
      let treeObj = $.fn.zTree.getZTreeObj("privilegeTree");
      if(this.isAllCheck==true){
        treeObj.checkAllNodes(true);
      }else{
        treeObj.checkAllNodes(false);
      }
      this.checkedSum = treeObj.getCheckedNodes(true).length;
    },
    toOpenAddGroupDialog(){
      this.addGroupForm.name = ''
      this.addGroupForm.remark = ''
      this.tabIndexForGroup = 1
      this.dialogVisibleForGroup=true;
      this.initParkTree('parkTree')
    },
    toOpenAddRoleDialog(){
      this.addRoleForm.name = ''
      this.addRoleForm.remark = ''
      this.tabIndexForRole = 1
      this.dialogVisibleForRole=true;
      this.initParkTreeForPower('privilegeTree')
    },
    //打开新增用户框
    toOpenAddUserDialog(){
      this.userForm = clearObject(this.userForm)
      this.getRoleList();
      this.getGroupList();
      this.tabIndex = 1
      this.dialogVisibleForUser=true
    },
    initParkTree (treeId) {//新增分组-初始化停车场树
      API.platform_manage.GetParkingGroupAreaParkTree({}).then(res => {
        $.fn.zTree.destroy(treeId);
        var settings = {
          check: {
              enable: true
          },
          data: {
              simpleData: {
                  enable: true
              }
          },
          view: {
              showIcon: false,
              showLine: false,
          }
        };
        $.fn.zTree.init($("#"+treeId), settings, res.data.children);

        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        treeObj.expandAll(true);
      },err => {});
    },
    bindParkingGroup (treeId){ //新增分组-绑定停车场
      var self = this;
      var tree = $.fn.zTree.getZTreeObj(treeId);
      var nodes = tree.getCheckedNodes(true);
      var parkList = [];
      for (var i = 0; i < nodes.length; i++) {
          if (!nodes[i].isArea) {
              parkList.push(nodes[i].value);
          }
      }
      if (parkList.length <= 0) {
          self.showToast('请至少选择一个停车场', 0);
          return false;
      }
      return parkList;
    },
    saveAddGroupModal(formName){ //新增分组-保存新增分组
      let self = this
      this.$refs[formName].validate((valid)=>{
        if(!valid){
          return false;
        }else{
          let params = $.extend({}, self.addGroupForm);
          let parkIdList = self.bindParkingGroup('parkTree');
          params.parkIdList = parkIdList
          API.platform_manage.SaveParkingGroupData(params).then(res =>{
            if(res.status==1){
              this.showToast("操作成功",1);
              this.dialogVisibleForGroup = false
              //获取分组列表
              this.getGroupList()
            }else{
              this.showToast("操作失败",2);
            }
          }, err => {});
        }
      })
    },
    initParkTreeForPower (treeId) {//新增角色-初始化权限树
      let self = this
      self.isAllCheck = false
      self.checkedSum = 0
      API.platform_manage.FindResourceForSetup({}).then(res => {
        $.fn.zTree.destroy(treeId);
        var settings = {
          check: {
              enable: true
          },
          data: {
              simpleData: {
                  enable: true
              }
          },
          view: {
              showIcon: false,
              showLine: false,
          },
          callback: {
            onCheck: self.zTreeOnCheck
          }
        };
        $.fn.zTree.init($("#"+treeId), settings, res.data);
        self.totalPowerNum = res.data.length
        let count = 0
        for(let i = 0; i<res.data.length; i++){
          let obj = res.data[i]
          count = obj.checked==true ? count+1 : count+0
        }
        self.checkedSum = count
      },err => {});
    },
    zTreeOnCheck(){
      let treeObj = $.fn.zTree.getZTreeObj("privilegeTree");
      this.checkedSum = treeObj.getCheckedNodes(true).length;
      if(this.checkedSum==this.totalPowerNum){
        this.isAllCheck = true
      }else{
        this.isAllCheck = false
      }
    },
    setPrivilege (treeId){ //新增角色-获取选取的权限数组
      var self = this;
      var tree = $.fn.zTree.getZTreeObj(treeId);
      var nodes = tree.getCheckedNodes(true);
      var parkList = [];
      for (var i = 0; i < nodes.length; i++) {
          if (!nodes[i].isArea) {
              parkList.push(nodes[i].id);
          }
      }
      if (parkList.length <= 0) {
          self.showToast('请至少选择一个权限', 0);
          return false;
      }
      return parkList;
    },
    saveAddRoleModal(formName){//新增角色-保存角色
      this.$refs[formName].validate((valid) => {
          if (!valid) {
            return false;
          }else{
            let params = $.extend({},this.addRoleForm)
            let resourceIdList = this.setPrivilege('privilegeTree')
            params.resourceIdList = resourceIdList
            API.platform_manage.SaveRoleData(params).then(res =>{
              if(res.status==1){
                this.showToast("操作成功",1);
                this.dialogVisibleForRole = false
                //获取角色列表
                this.getRoleList()
              }else{
                this.showToast("操作失败",2);
              }
            }, err => {});
          }
      });
    },
    //获取角色列表
    getRoleList(){
      let self = this
      API.platform_manage.FindRoleForSetup({}).then(res=>{
        let data = res.data
        self.chooseRoleList = []
        self.allRoleList = data.all
      },err=>{})
    },
    //获取分组列表
    getGroupList(){
      let self = this
      API.platform_manage.FindParkGroupForSetup({}).then(res=>{
        let data = res.data
        self.chooseGroupList = []
        self.allGroupList = data.all
      },err=>{})
    },
    toOpenAddRoleModal(modalName){
      this.toOpenModal(modalName,2);
    },
    getList () {
      this.getAllUserList(this.searchParams);
    },
    getAllUserList (aparams) {//查询列表
      let self = this,
          params = {
            page: this.pageNumber,
            rp: this.pageSize
          };
      params = $.extend({}, params, aparams);
      API.platform_manage.GetUserListData(params)
          .then(res => {
            let data = res.data,
                list = data.rows;
            self.tbodysInfo = list;
            self.total = data.total;
          }, err => {})
    },
    toOpenUserAdd (modalName) {//打开新增
      clearObject(this.userForm);
      this.toOpenModal(modalName);
    },
    toOpenUserEdit (row,modalName){//打开编辑
      copyObjBySelf(this.userEditForm,row);
      this.toOpenModal(modalName);
    },
    toOpenPwdEdit(row,modalName){//打开密码修改
      this.pwdForm.userID = row.id;
      this.pwdForm.loginId = row.loginId;
      this.toOpenModal(modalName,1);
    },
    filterMultiCheck (selectionArr) {//必须定义获取多列的方法
      let result = [];
        selectionArr.map((item)=>{
          result.push(item.id);
        });
      return result;
    },
    toOpenUserDelete(row){//打开删除对话框
      let self = this;
      let ids = [];
      if(row){
        //单行
        ids.push(row.id);
      }else{
        //判断是否选择了多行
        let idsStr = this.selectionList;
        if(idsStr<=0){
          this.showToast("请至少选择一项",0);
          return false;
        }else{
          ids = idsStr.split(",");
        }
      }
      this.showDialog("是否确认删除所选记录？",[],function(){
        API.platform_manage.DeleteUserBatch({"JSONSTRING":JSON.stringify(ids)}).then(res => {
          if(res.status==1){
            self.getList();
            self.showToast("操作成功",1);
          }else{
            self.showToast("操作失败",2);
          }
        }, err =>{});
      },"温馨提示",function(){
        //取消时不操作
      });
    },
    toOpenRoleSetting(row,modalName){//打开角色设置
      this.roleForm.loginId = row.loginId;
      this.roleForm.userID = row.id;
      this.findRoleForSetup(row);
      this.toOpenModal(modalName);
    },
    findRoleForSetup(row){//查找角色设置用的角色数据
      let self = this;
      API.platform_manage.FindRoleForSetup({"userID":row.id}).then(res => {
        let data = res.data;
        self.leftRoleArr = data.all;
        self.rightRoleArr = data.setups;
      },err => {});
    },
    setRoleForUser(modalName) {//保存角色设置
      let self = this;
      API.platform_manage.SetRoleForUser({ "id": this.roleForm.userID, "roleIdList": this.rightRoleArr }).then(res => {
        let sta = res.status;
        if (res.status == 1) {
          self.closed(modalName);
          self.showToast("设置成功", 1);
        } else {
          self.showToast("设置失败", 2);
        }
      }, err => { });
    },
    toOpenParkGroupSetting(row,modalName){//打开停车场分组设置
      this.parkGroupForm.loginId = row.loginId;
      this.parkGroupForm.userID = row.id;
      this.findParkGroupForSetup(row);
      this.toOpenModal(modalName);
    },
    findParkGroupForSetup(row){//查找停车场分组设置用的分组数据
      let self = this;
      API.platform_manage.FindParkGroupForSetup({"userID":row.id}).then(res => {
        let data = res.data;
        self.leftParkArr = data.all;
        self.rightParkArr = data.setups;
      },err => {});
    },
    setParkGroupForUser(modalName) {//保存停车场分组设置
      let self = this;
      API.platform_manage.SetParkGroupForUser({ "id": this.parkGroupForm.userID, "parkGroupIdList": this.rightParkArr }).then(res => {
        let sta = res.status;
        if (res.status == 1) {
          self.closed(modalName);
          self.showToast("设置成功", 1);
        } else {
          self.showToast("设置失败", 2);
        }
      }, err => { });
    },
    resetPwd(formName,modalName){//重置密码
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        } else {
          API.platform_manage.ResetPassword(this.pwdForm).then(res => {
            let sta = res.status;
            if (res.status == 1) {
              this.closed(modalName);
              this.getList();
              this.showToast("操作成功", 1);
            } else {
              this.showToast("操作失败", 2);
            }
          }, err => { });
        }
      });
    },
    saveUserForm(formName,modalName){//保存用户
      this.$refs[formName].validate((valid) => {
          if (!valid) {
            return false;
          }else{
            let pa = null;
            if(formName == 'userEditForm'){
              pa = this.userEditForm;
            }else{
              if(this.chooseRoleList.length<=0){
                this.showToast('请至少选择一个角色',0)
                return
              }
              if(this.chooseGroupList.length<=0){
                this.showToast('请至少选择一个分组',0)
                return
              }
              pa = this.userForm;
              pa.roleIdList = this.chooseRoleList
              pa.parkGroupIdList = this.chooseGroupList
            }
            API.platform_manage.SaveUserData(pa).then(res =>{
              if(res.status==1){
                if(modalName!=null){
                  this.closed(modalName);
                }
                this.dialogVisibleForUser = false
                this.getList();
                this.showToast("操作成功",1);
              }else{
                this.showToast("操作失败",2);
              }
            }, err => {});

          }
      });
    },
  }
}